package com.yikaiye.android.yikaiye.ui.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityConfirmOrderBinding;
import com.yikaiye.android.yikaiye.http.ApiFactory;
import com.yikaiye.android.yikaiye.model.CommitOrderModel;
import com.yikaiye.android.yikaiye.model.CompanyRecordsModel;
import com.yikaiye.android.yikaiye.model.PayResult;
import com.yikaiye.android.yikaiye.pay.WeChatPay;
import com.yikaiye.android.yikaiye.ui.activity.home.viewmodel.ConfirmOrderViewModel;
import com.yikaiye.android.yikaiye.ui.activity.order.ChooseCompanyActivity;
import com.yikaiye.android.yikaiye.ui.activity.order.OrderResultActivity;
import com.yikaiye.android.yikaiye.ui.adapter.EmptyRecyclerCommonAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.RecyclerViewHolder;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.SpanContentParser;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 确认订单
 */
public class ConfirmOrderActivity extends BaseActivity<ActivityConfirmOrderBinding, ConfirmOrderViewModel> {

    private ActivityResultLauncher<Intent> searchLauncher;
    private static final int SDK_PAY_FLAG = 1;
    private List<CommitOrderModel.Item> data = new ArrayList<>();
    /**
     * 0支付宝、1微信
     */
    private int payType = 0;
    private CommitOrderModel commitOrderModel;
    private CompanyRecordsModel.CompanyModel chooseCompanyModel;

    @Override
    protected ConfirmOrderViewModel bindModel() {
        return getViewModel(this, ConfirmOrderViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.confirm_order));
        UMengUtil.setCountEventId(Constant.PAGE_CONFIRM_ORDER);
        SpanContentParser span = new SpanContentParser();
        span.setBookCharListener(name -> {
            if (!CommonUtil.isCanClick()) return;
            ToastHelper.show(name);
        });
        viewModel.getMyCompanyList(1, null);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            commitOrderModel = (CommitOrderModel) bundle.getSerializable(Constant.MODEL_KEY);
            if (null != commitOrderModel) {
                if (null != commitOrderModel.getItems()) {
                    data = commitOrderModel.getItems();
                }
                String des = bundle.getString(Constant.DES_KEY);
                String img = bundle.getString(Constant.IMG_KEY);
                binding.tvTitle.setText(commitOrderModel.getProductName());
                binding.tvDes.setText(des);
                Glide.with(MyApplication.getContext()).load(ApiFactory.BASE_IMAGE_URL + img).placeholder(R.mipmap.default_image).error(R.mipmap.default_image).into(binding.ivProductImg);
                binding.include.tvServiceTotalPrice.setText(getString(R.string.total_price, commitOrderModel.getPrice()));
                binding.include.tvServiceRealPrice.setText(commitOrderModel.getPrice());
                binding.tvTotalPrice.setText(getString(R.string.price, commitOrderModel.getPrice()));
            }
            Log.e("@@@@@@@@", new Gson().toJson(commitOrderModel));
        }

        if (TextUtils.isEmpty(MyApplication.manager.getRealName())) {
            binding.tvName.setText(TextUtils.isEmpty(MyApplication.manager.getUsername()) ? getString(R.string.common_user) : MyApplication.manager.getUsername());
            binding.tvCompanyName.setVisibility(View.GONE);
        } else {
            binding.tvName.setText(MyApplication.manager.getRealName());
        }

        binding.tvPhone.setText(MyApplication.manager.getPhone());
        searchLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    chooseCompanyModel = (CompanyRecordsModel.CompanyModel) result.getData().getExtras().get(Constant.MODEL_KEY);
                    if (chooseCompanyModel != null) {
                        binding.tvCompanyName.setVisibility(View.VISIBLE);
                        binding.tvCompanyName.setText(chooseCompanyModel.getEnterpriseName());
                    }
                }
            }
        });
    }

    @Override
    public void initCtrl() {
        EmptyRecyclerCommonAdapter<CommitOrderModel.Item> adapter = new EmptyRecyclerCommonAdapter<CommitOrderModel.Item>(context, R.layout.item_confirm_order_service_layout, data) {
            @Override
            public void convert(RecyclerViewHolder holder, CommitOrderModel.Item item, int position) {
                if (item.getServiceType() == 1) {
                    // 服务属性周期类型 0表示月,1表示年
                    if (item.getServiceAttrCycleType() == 0) {
                        holder.setText(R.id.tv_service_name, getString(R.string.cycle_month, item.getTerminalName(), item.getBookPeriod()));
                    } else if (item.getServiceAttrCycleType() == 1) {
                        holder.setText(R.id.tv_service_name, getString(R.string.cycle_year, item.getTerminalName(), item.getBookPeriod()));
                    }
                } else {
                    holder.setText(R.id.tv_service_name, item.getTerminalName() + " * " + item.getBookPeriod());
                }
                holder.setText(R.id.tv_service_price, getString(R.string.price, item.getPrice()));
            }
        };
        binding.include.recyclerViewService.setAdapter(adapter);
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.llCompanyName, o -> {
            Intent intent = new Intent(ConfirmOrderActivity.this, ChooseCompanyActivity.class);
            searchLauncher.launch(intent);
        });

        viewModel.onDelayClick(binding.includePay.rlZhi, o -> {
            payType = 0;
            binding.includePay.ivZhiStatus.setImageResource(R.mipmap.icon_duigou_sel);
            binding.includePay.ivWeStatus.setImageResource(R.mipmap.icon_duigou_def);
        });

        viewModel.onDelayClick(binding.includePay.rlWe, o -> {
            payType = 1;
            binding.includePay.ivZhiStatus.setImageResource(R.mipmap.icon_duigou_def);
            binding.includePay.ivWeStatus.setImageResource(R.mipmap.icon_duigou_sel);
        });

        viewModel.onDelayClick(binding.tvPay, o -> {
            UMengUtil.setCountEventId(Constant.PAGE_CONFIRM_ORDER_PAY);
            if (payType == 1) {
                if (!MyApplication.wxapi.isWXAppInstalled()) {
                    ToastHelper.show(getString(R.string.please_install_wechat));
                    return;
                }
            }
            showLoadingDialog();
            if (chooseCompanyModel != null) {
                commitOrderModel.setEnterConfirmState(1);
                commitOrderModel.setCompName(chooseCompanyModel.getEnterpriseName());
                commitOrderModel.setCreditNo(chooseCompanyModel.getCreditNo());
            }
            Log.e("@@@@@@====", new Gson().toJson(commitOrderModel));
            // 提交订单
            viewModel.commitOrder(new Gson().toJson(commitOrderModel));
        });

        // 我的企业列表，默认选择第一个
        viewModel.companyRecordsModelMutableLiveData.observe(this, companyRecordsModel -> {
            if (companyRecordsModel != null) {
                if (companyRecordsModel.getRecords() != null && !companyRecordsModel.getRecords().isEmpty()) {
                    binding.tvCompanyName.setVisibility(View.VISIBLE);
                    chooseCompanyModel = companyRecordsModel.getRecords().get(0);
                    binding.ivNext.setVisibility(companyRecordsModel.getRecords().size() == 1 ? View.GONE : View.VISIBLE);
                    binding.llCompanyName.setClickable(companyRecordsModel.getRecords().size() != 1);
                    if (chooseCompanyModel != null && !TextUtils.isEmpty(chooseCompanyModel.getEnterpriseName())) {
                        binding.tvCompanyName.setText(chooseCompanyModel.getEnterpriseName());
                    }
                } else {
                    binding.llCompanyName.setClickable(false);
                    binding.tvCompanyName.setVisibility(View.GONE);
                    binding.ivNext.setVisibility(View.GONE);
                }
            }
        });
        // 提交订单成功
        viewModel.commitOrderSuccessMutableLiveData.observe(this, commitOrderResultModel -> {
            if (commitOrderResultModel != null) {
                Map<String, Object> map = new HashMap<>();
                if (chooseCompanyModel != null) {
                    map.put("enterConfirmState", 1);
                    map.put("companyName", chooseCompanyModel.getEnterpriseName());
                    map.put("creditNo", chooseCompanyModel.getCreditNo());
                }
                if (payType == 0) {
                    viewModel.getAliPay(commitOrderResultModel.getId(), new Gson().toJson(map));
                } else {
                    viewModel.getWeChatPay(commitOrderResultModel.getId(), new Gson().toJson(map));
                }
            }
        });
        // 提交订单失败
        viewModel.commitOrderErrorMutableLiveData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });

        // 微信支付
        viewModel.wechatPaySuccessMutableLiveData.observe(this, weChatInfoModel -> {
            dismissLoadingDialog();
            new WeChatPay().pay(context, weChatInfoModel);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, 1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });
        viewModel.wechatPayErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });

        // 支付宝
        viewModel.aliPaySuccessMutableLiveData.observe(this, alipayModel -> {
            alipay(alipayModel.getBody());
            dismissLoadingDialog();
        });
        viewModel.aliPayErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });
    }

    private void alipay(String info) {
        // 订单信息
        final String orderInfo = info;
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(ConfirmOrderActivity.this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private final MyHandler mHandler = new MyHandler(Looper.myLooper(), this);

    private static class MyHandler extends Handler {

        WeakReference<ConfirmOrderActivity> mActivity;

        public MyHandler(@NonNull Looper looper, ConfirmOrderActivity activity) {
            super(looper);
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == SDK_PAY_FLAG) {
                @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();// 同步返回需要验签的信息，对应map集合中key为result对应的value值。
                String resultStatus = payResult.getResultStatus();
                Bundle bundle = new Bundle();
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 同步通知验证,在返回数据resultStatus为9000的情况下，继续解析resultInfo字符串，进行验签
//                    ToastHelper.show("验签通过后才能证明支付成功" + payResult);
                    bundle.putInt(Constant.RESULT_STATUS_KEY, 1);
                } else if (TextUtils.equals(resultStatus, "6001")) {
//                    ToastHelper.show("支付取消");
                    bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
                } else {
//                    ToastHelper.show("支付失败");
                    bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
                }
                JumpIntent.jump(mActivity.get(), OrderResultActivity.class, bundle);
            }
        }
    }
}